
var crypt = require('md5.js');

/*
  1.过期
  2.不过期
*/
function wxlogin(domain, url, data, callback, rtype) {
  
  /*wx.checkSession({
    success: function () {
      //session 未过期，并且在本生命周期一直有效
    },
    fail: function () {*/
      //登录态过期

      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {

            var timestamp = new Date().getTime();

            //发起网络请求
            wx.request({
              url: domain + '/index.php/Web/XcxLogin/login.html',
              data: {
                code: res.code,
                time: timestamp,
                sign: crypt.md5(res.code + timestamp + 'xcxlogin')
              },
              success: function (res) {
                //console.log(res.data);
                if (res.data.errcode==200) {
                  wx.setStorageSync('session', res.data.msg);
                }
                request1(domain, url, data, callback, rtype);
              }
            })

          } else {
            //console.log('获取用户登录态失败！' + res.errMsg)
            request1(domain, url, data, callback, rtype)
          }

        },
        fail: res => {
          request1(domain, url, data, callback, rtype)
        }
      })
     
  //   }
  // })

}


function getUserInfo(obj) {

  wx.getSetting({
    success: res => {
      if (res.authSetting['scope.userInfo']) {
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        wx.getUserInfo({
          success: res => {
            obj.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
            wx.setStorageSync('userInfo', res.userInfo);
          }
        })
      }
      else {
        obj.setData({
          userInfo: {},
          hasUserInfo: false
        })
      }
    }
  })

}


/*

*/
function request1(domain, url, data, callback, rtype='get') {

  var session = wx.getStorageSync('session');
  var expire = session.expire ? session.expire : 0;

  var timestamp = Math.round(new Date().getTime()/1000);

  //console.log(rtype);return;
  //过期，更新已绑定
  if (timestamp >= (expire-1800)) {
    wxlogin(domain, url, data, callback, rtype)
  }
  else {
    request1(domain, url, data, callback, rtype)
  }

}


function request(domain, url, data, callback, rtype='get') {
  var session = wx.getStorageSync('session');
  var uid = session.uid ? session.uid : '';
  var token = session.token ? session.token : '';
  var expire = session.expire ? session.expire : 0;

  var timestamp = Math.round(new Date().getTime() / 1000);
  var noncestr = Math.random();

  var signature = crypt.md5(uid + token + timestamp + noncestr + url);
  //console.log(uid + token + timestamp + noncestr + url);
  data.uid = uid;
  data.sign_timestamp = timestamp;
  data.sign_noncestr = noncestr;
  data.sign_signature = signature;

  if (rtype=='get') {
    wx.request({
      url: domain + url,
      data: data,
      success: function (res) {
        if (res.data.errcode == 100) {
          wx.navigateTo({
            url: '/pages/my/register/register'
          })
          return;
        }

        callback(res)
      }
    })
  }
  else {
    wx.request({
      url: domain + url,
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.errcode == 100) {
          wx.navigateTo({
            url: '/pages/my/register/register'
          })
          return;
        }

        callback(res)
      }
    })
  }
  
}


function session_auth() {
  var session = wx.getStorageSync('session');
  var uid = session.uid ? session.uid : '';

  if (uid) {
    return true;
  }
  else {
    wx.navigateTo({
      url: '/pages/my/register/register'
    })
    return false;
  }
}


function set_storage_storeid(url) {
  if (url==undefined) {
    return;
  }

  var p0 = decodeURIComponent(url);
  var p1 = p0.split('?');
  var p2 = p1[1].split('&');

  var p3 = p2[0].split('=');
  var storeid = p3[1];

  var p4 = p2[1].split('=');
  var id = p4[1];

  wx.setStorageSync('storeid', storeid);
  wx.setStorageSync('storeclass', id);
  wx.setStorageSync('qrcodestore', true);

  return;
}






//module.exports.wxlogin = wxlogin
module.exports.getUserInfo = getUserInfo
module.exports.request = request
module.exports.session_auth = session_auth
//module.exports.request1 = request1

module.exports.set_storage_storeid = set_storage_storeid